package com.jamaskii.dictation;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.FileProvider;

import com.jamaskii.ecdict.PronunciationStream;
import com.jamaskii.ecdict.Word;
import com.jamaskii.ecdict.WordBook;
import com.jamaskii.thread.Task;
import com.jamaskii.thread.TaskGroup;

import java.io.File;
import java.util.ArrayList;

public class BookActivity extends BaseActivity {

    public int index=-1;
    private ItemAdapter itemAdapter;
    public static BookActivity instance;
    final public static Handler hand=new Handler();
    public WordBook book;
    public PronunciationStream pronunciationStream;


    public int getStatueBarHeight(){
        int statusBarHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusBarHeight = getResources().getDimensionPixelSize(height);
            return statusBarHeight;
        } catch (Exception e) {
            return 24;
        }
    }

    private void setTopPadding(){
        ConstraintLayout layout=findViewById(R.id.padding) ;
        ViewGroup.LayoutParams layoutParams=layout.getLayoutParams();
        layoutParams.height=getStatueBarHeight();
        layout.setLayoutParams(layoutParams);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book);
        instance=this;
        init();
    }

    private void init(){
        setTopPadding();
        index=getIntent().getExtras().getInt("index");
        book=HomeActivity.instance.wordBookStream.wordBooks.get(index);
        setOnBackClick();
        loadBookInfo();

        TextView labelTitle=findViewById(R.id.label_title);
        labelTitle.getPaint().setFakeBoldText(true);

        showWords();
        setItemOnClick();

        pronunciationStream=new PronunciationStream(getExternalFilesDir(null).getAbsolutePath()+"/porn/");
    }

    private void loadBookInfo(){
        TextView textView=findViewById(R.id.label_title);
        textView.setText(book.name);
    }

    private void setOnBackClick(){
        ImageView imageView=findViewById(R.id.image_back);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    public void onEditClick(View view){
        final View layoutRenameBook=getLayoutInflater().inflate(R.layout.dialog_input,null);
        final EditText textBoxNewName=layoutRenameBook.findViewById(R.id.textbox_content_input_dialog);
        textBoxNewName.setText(book.name);

        AlertDialog.Builder builder=new AlertDialog.Builder(BookActivity.this);
        builder.setTitle("新名称");
        builder.setView(layoutRenameBook);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        });
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String newName=textBoxNewName.getText().toString();
                boolean notChanged=newName.equals(book.name);
                if(newName.isEmpty() || notChanged){
                    return;
                }
                if(HomeActivity.instance.wordBookStream.renameBook(index,newName)){
                    HomeActivity.instance.loadBooks();
                    HomeActivity.instance.linkData();
                    book=HomeActivity.instance.wordBookStream.wordBooks.get(index);
                    loadBookInfo();
                }else{
                    String error=HomeActivity.instance.wordBookStream.error;
                    if(error.equals("BookNameDuplicateException")){
                        Toast.makeText(BookActivity.this, "修改失败:与已有单词本名称重复", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(BookActivity.this, error, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        AlertDialog dialog=builder.create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(BookActivity.this.getResources().getColor(R.color.themeColor));
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(BookActivity.this.getResources().getColor(R.color.themeColor));
    }

    public void showWords(){
        ListView listView=findViewById(R.id.list_words);
        ArrayList<Word> words=book.words;
        ArrayList<ItemData> items=new ArrayList<>();
        for (Word word:words
             ) {
            ItemData item=new ItemData(word,ItemType.SHOW_WORD);
            items.add(item);
        }
        ItemData addItem=new ItemData(ItemType.ADD_WORD);
        items.add(addItem);
        ItemData shareItem=new ItemData(ItemType.SHARE_BOOK);
        items.add(shareItem);
        itemAdapter=new ItemAdapter(this,R.layout.item_book_manager,items);
        listView.setDivider(getDrawable(R.color.lineGray));
        listView.setDividerHeight(1);
        listView.setAdapter(itemAdapter);
    }

    private void setItemOnClick(){
        final ListView listView=findViewById(R.id.list_words);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(i==itemAdapter.getCount()-1){
                    showShareDialog();
                }else if (i==itemAdapter.getCount()-2){
                    showAddWordDialog();
                }else{
                    AlertDialog dialog=new AlertDialog.Builder(BookActivity.this).create();
                    dialog.setTitle(book.words.get(i).name);
                    dialog.setMessage(book.words.get(i).translated);
                    dialog.show();
                }
            }
        });
    }

    private void showShareDialog(){
        File file=new File(HomeActivity.instance.wordBookStream.path+"/"+book.name+".wb");
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        //Generate the uri by api level
        try
        {
            Uri uri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(this, this.getPackageName()+".FileProvider", file);
            } else {
                uri = Uri.fromFile(file);
            }
            intent.setDataAndType(uri, "*/*");

            intent.setAction(Intent.ACTION_VIEW);
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Intent chooser = Intent.createChooser(intent, null);
            startActivity(chooser);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void showAddWordDialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        ListView listChoices=new ListView(this);
        builder.setView(listChoices);
        String[] choices=new String[]{"添加单个","添加多个"};
        ArrayAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,choices);
        listChoices.setAdapter(adapter);
        final AlertDialog dialog=builder.create();
        listChoices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                dialog.cancel();
                switch (i){
                    case 0:
                        addSingle();
                        break;
                    case 1:
                        addMulti();
                        break;
                }
            }
        });
        dialog.show();
    }


    private void addMulti(){
        Intent intent=new Intent();
        intent.setClass(BookActivity.this,MultiAddActivity.class);
        startActivity(intent);
    }

    private void addSingle(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("新单词");
        final View view=getLayoutInflater().inflate(R.layout.dialog_input,null);
        final EditText textBoxContent=view.findViewById(R.id.textbox_content_input_dialog);
        textBoxContent.setText("");
        builder.setView(view);
        builder.setPositiveButton("添加", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Thread thread=new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String text=textBoxContent.getText().toString();
                        if(!text.isEmpty()){
                            Word word=Word.matchOnline(text);
                            if(word==null){
                                HomeActivity.instance.showMessage("联网匹配失败！");
                            }else{
                                book.words.add(word);
                                book.save(HomeActivity.instance.wordBookStream.path);
                                hand.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        showWords();
                                    }
                                });
                            }
                        }
                    }
                });
                thread.start();
            }
        });
        builder.setNegativeButton("取消",null);
        AlertDialog dialog=builder.create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.themeColor));
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.themeColor));
    }

    public void onManageClick(View view){
        Intent intent=new Intent();
        intent.setClass(BookActivity.this,WordsManageActivity.class);
        startActivity(intent);
    }

    public void startDictation(View view){
        if(book.words.size()==0){
            return;
        }
        final TaskGroup group=new TaskGroup();
        final ProgressDialog dialog=new ProgressDialog(this);
        for (final Word word:book.words
             ) {
            if(pronunciationStream.getPronunciation(word.name,0)==null){
                Task task=new Task(new Runnable() {
                    @Override
                    public void run() {
                        pronunciationStream.downloadPronunciation(word.name,0);
                    }
                });
                task.onDone=new Runnable() {
                    @Override
                    public void run() {
                        dialog.setMessage("进度："+group.getDoneTask().size()+"/"+group.tasks.size());
                    }
                };
                group.tasks.add(task);
            }
            if(pronunciationStream.getPronunciation(word.name,1)==null){
                Task task=new Task(new Runnable() {
                    @Override
                    public void run() {
                        pronunciationStream.downloadPronunciation(word.name,1);
                    }
                });
                task.onDone=new Runnable() {
                    @Override
                    public void run() {
                        dialog.setMessage("进度："+group.getDoneTask().size()+"/"+group.tasks.size());
                    }
                };
                group.tasks.add(task);
            }
        }
        if(group.tasks.size()==0){
            showDictation();
        }else{
            dialog.setTitle("下载发音");
            dialog.setCancelable(false);
            dialog.show();
            group.start(8, new Runnable() {
                @Override
                public void run() {
                    hand.post(new Runnable() {
                        @Override
                        public void run() {
                            dialog.cancel();
                            showDictation();
                        }
                    });
                }
            });
        }

    }

    private void showDictation(){
        Intent intent=new Intent();
        intent.setClass(BookActivity.this,DictationActivity.class);
        startActivity(intent);
    }


}